from QQLoginTool.QQtool import OAuthQQ
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView

from carts.utils import merge_cookie_redis_cart
from mall import settings
from oauth.sinaweibopy3 import APIClient
from oauth.utils import generate_sign_openid
from .models import OAuthQQUser, OAuthSinaUser
from . import serializers


class OAuthQQLoginView(APIView):
    """获取qq第三方登录页面"""

    def get(self, request):
        # 1,获取参数
        state = request.query_params.get("state", "/")

        # 2,创建qq对象
        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                           client_secret=settings.QQ_CLIENT_SECRET,
                           redirect_uri=settings.QQ_REDIRECT_URI,
                           state=state)

        # 3,返回qq登陆页面
        login_url = oauth_qq.get_qq_url()
        return Response({"auth_url": login_url})


class OAuthQQUserView(GenericAPIView):
    serializer_class = serializers.OAuthQQUserSerializer

    def get(self, request):
        # 1,获取参数code,校验
        code = request.query_params.get("code")
        if not code:
            return Response("code丢失了")

        # 2,根据code获取access_token
        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                           client_secret=settings.QQ_CLIENT_SECRET,
                           redirect_uri=settings.QQ_REDIRECT_URI,
                           state="/")
        access_token = oauth_qq.get_access_token(code)

        # 3,根据access_token获取openid
        openid = oauth_qq.get_open_id(access_token)

        # 4,通过openid查询qq对象用户
        try:
            oauth_qq_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 4,1初次授权
            sign_openid = generate_sign_openid(openid)
            return Response({"access_token": sign_openid})
        else:
            # 5,非初次授权
            user = oauth_qq_user.user

            from rest_framework_jwt.settings import api_settings
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            # 合并购物车,返回
            response = Response({
                "token": token,
                "username": user.username,
                "user_id": user.id
            })

            response = merge_cookie_redis_cart(request, user, response)

            return response

    def post(self, request):
        # 1,获取参数
        dict_data = request.data

        # 2,创建序列化器
        serializer = self.get_serializer(data=dict_data)

        # 3,校验,入库
        serializer.is_valid(raise_exception=True)
        user = serializer.save()

        # 3,1根据用户数据,生成token
        from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 合并购物车,返回
        response = Response({
            "token": token,
            "username": user.username,
            "user_id": user.id
        })

        response = merge_cookie_redis_cart(request, user, response)

        return response


class OAuthSinaLoginView(APIView):
    """获取微博第三方登录"""

    def get(self, request):
        # 1,获取参数
        state = request.query_params.get("state", "/")

        # 2,创建微博对象
        oauth_sina = APIClient(app_key=settings.SINA_APP_KEY,
                               app_secret=settings.SINA_APP_SECRET,
                               redirect_uri=settings.SINA_REDIRECT_URI)

        # 3,返回微博登陆页面
        login_url = oauth_sina.get_authorize_url()
        return Response({"auth_url": login_url})


class OAuthSinaUserView(GenericAPIView):
    """微博登录类视图"""
    serializer_class = serializers.OAuthSinaUserSerializer

    def get(self, request):
        # 获取参数
        code = request.query_params.get("code",None)
        # 判断code是否存在
        if not code:
            return Response("code丢失了")

        # 根据code获取access_token
        oauth_sina = APIClient(app_key=settings.SINA_APP_KEY,
                               app_secret=settings.SINA_APP_SECRET,
                               redirect_uri=settings.SINA_REDIRECT_URI)
        try:
            access_token = oauth_sina.request_access_token(code).get('access_token')
            # print("code:%s" % code)
        except:
            return Response("微博服务器异常",status=400)
        # 根据access_token获取openid
        # openid = oauth_sina.set_access_token(access_token.access_token, expires_in=access_token.expires_in)
        # print("openid:%s" % openid)
        try:
            oauth_sina_user = OAuthSinaUser.objects.get(openid=access_token)
        except OAuthSinaUser.DoesNotExist:
            # 初次授权
            sign_openid = generate_sign_openid(access_token)
            return Response({"access_token": sign_openid})

        # 非初次授权
        user = oauth_sina_user.user
        from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 拼接数据
        response = Response({
            "user_id": user.id,
            "username": user.username,
            "token": token,
        })

        response = merge_cookie_redis_cart(request=request,
                                           user=user,
                                           response=response)
        return response

    def post(self, request):
        # 获取参数
        dict_data = request.data
        # 获取序列化器对象
        serializer = self.get_serializer(data=dict_data)
        serializer.is_valid(raise_exception=True)

        # 校验,入库
        user = serializer.save()
        from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 拼接数据
        response = Response({
            "token": token,
            "username": user.username,
            "user_id": user.id
        })

        response = merge_cookie_redis_cart(request, user, response)

        return response
